package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author junyong
 * @since 2024-8-10
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    public Result isFollowed(Long id) {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.从Redis中查是否已经关注
        Boolean isFollowed = stringRedisTemplate.opsForSet().isMember(FOLLOW_KEY + userId, id.toString());
        return Result.ok(BooleanUtil.isTrue(isFollowed));
    }

    /**
     * 关注/取关
     *
     * @param id
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long id, boolean isFollow) {

        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        if (isFollow) {
            // 2.关注
            // 2.1写入数据库
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean isSuccess = save(follow);
            // 2.2写入Redis
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(FOLLOW_KEY + userId, id.toString());
            }
        } else {
            // 3.取消关注
            // 3.1从数据库中删除
            boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", id));
            // 3.2从Redis中删除
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(FOLLOW_KEY + userId, id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result commonFollow(Long id) {
        // 1.拿到当前登录用户id
        Long userId = UserHolder.getUser().getId();
        // 2.基于Redis的Set查询共同关注
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(FOLLOW_KEY + userId, FOLLOW_KEY + id);
        if(intersect == null || intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        // 3.拿到共同关注UserDTO信息
        List<UserDTO> userDTOS = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
